import React, { useState, useEffect, useCallback, useRef } from 'react'
import { Card, Input, Button, Empty, Spin, Space, Typography, Divider, Tooltip, Modal, message, Radio, FloatButton, Drawer, Form, Tabs, Upload } from 'antd'
import { SaveOutlined, InfoCircleOutlined, ExclamationCircleOutlined, SearchOutlined, ArrowUpOutlined, ArrowDownOutlined, SyncOutlined, SettingOutlined, DownloadOutlined, UploadOutlined, FilterOutlined } from '@ant-design/icons'
import { useParams } from 'react-router-dom';
import './TranslationEditor.css'

const { Text, Title } = Typography
const { TextArea } = Input
const { Search } = Input
const { confirm } = Modal

const API_HOST = window.location.hostname;
const API_PORT = 3001;
const WS_URL = `ws://${API_HOST}:${API_PORT}`;
const API_BASE_URL = `http://${API_HOST}:${API_PORT}`;

const TranslationEditor = () => {
  const { editorId } = useParams();
  const [translations, setTranslations] = useState([])
  const [searchTerm, setSearchTerm] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [editedItems, setEditedItems] = useState(new Set())
  const [unsavedCount, setUnsavedCount] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalCount, setTotalCount] = useState(0)
  const [hasMoreUp, setHasMoreUp] = useState(false)
  const [hasMoreDown, setHasMoreDown] = useState(true)
  const scrollContainerRef = useRef(null)
  const [isScrolling, setIsScrolling] = useState(false)
  const [lockedItems, setLockedItems] = useState(new Set())
  const [proofreadFilter, setProofreadFilter] = useState('not_proofread') // 'all', 'proofread', 'not_proofread'
  const ws = useRef(null)
  
  // 同步功能相关状态
  const [syncDrawerVisible, setSyncDrawerVisible] = useState(false)
  const [syncConfig, setSyncConfig] = useState({
    projectPath: '',
    targetPath: ''
  })
  const [isSyncing, setIsSyncing] = useState(false)
  const [syncLogs, setSyncLogs] = useState([])
  const [showSyncLogs, setShowSyncLogs] = useState(false)
  const [form] = Form.useForm()

  // WebSocket连接
  useEffect(() => {
    ws.current = new WebSocket(WS_URL)

    ws.current.onopen = () => {
      console.log('WebSocket connected')
    }

    ws.current.onmessage = (event) => {
      const message = JSON.parse(event.data)
      
      switch (message.type) {
        case 'startEditing':
          setLockedItems(prev => new Set(prev).add(message.id))
          break
        case 'stopEditing':
          setLockedItems(prev => {
            const newSet = new Set(prev)
            newSet.delete(message.id)
            return newSet
          })
          break
        case 'updateTranslation':
          setTranslations(prev => 
            prev.map(t => t.id === message.id ? { ...t, translation: message.translation } : t)
          )
          break
        case 'translationSaved':
          setTranslations(prev => 
            prev.map(t => 
              t.id === message.id 
                ? { ...t, translation: message.translation, originalTranslation: message.translation, isModified: false } 
                : t
            )
          )
          setLockedItems(prev => {
            const newSet = new Set(prev)
            newSet.delete(message.id)
            return newSet
          })
          break
        case 'proofreadStatusChanged':
          setTranslations(prev =>
            prev.map(t =>
              t.id === message.id ? { ...t, isProofread: message.isProofread } : t
            )
          );
          break
        case 'sync_log':
          setSyncLogs(prev => [...prev, { 
            timestamp: new Date().toLocaleTimeString(), 
            message: message.log 
          }])
          // 如果正在同步，自动显示日志窗口
          if (message.log.includes('[SYNC] 开始同步数据')) {
            setShowSyncLogs(true)
            setSyncLogs([{ timestamp: new Date().toLocaleTimeString(), message: message.log }])
          }
          break
        default:
          break
      }
    }

    ws.current.onclose = () => {
      console.log('WebSocket disconnected')
    }

    return () => {
      ws.current.close()
    }
  }, [])

  // 加载翻译数据
  const loadTranslations = useCallback(async (page = 1, search = '', direction = 'replace') => {
    if (isLoading) return
    
    setIsLoading(true)
    if (direction === 'up' || direction === 'down') {
      setIsScrolling(true)
    }

    try {
      const params = new URLSearchParams()
      params.append('page', page.toString())
      params.append('limit', '20')
      params.append('proofreadStatus', proofreadFilter)
      
      if (search.trim()) {
        params.append('search', search.trim())
      }
      
      if (editorId) {
        params.append('editorId', editorId);
      }

      const response = await fetch(`${API_BASE_URL}/api/translations?${params}`)
      const result = await response.json()
      
      if (result.success) {
        const { data, totalCount: total, currentPage: fetchedPageNum } = result
        
        const enhancedData = data.map(item => ({
          ...item,
          originalTranslation: item.translation,
          isModified: false,
        }))
        
        setTotalCount(total)
        
        if (direction === 'down') {
          setCurrentPage(fetchedPageNum)
          setHasMoreUp(fetchedPageNum > 1)
          setHasMoreDown(fetchedPageNum * 20 < total)

          const newTranslations = [...translations, ...enhancedData]
          if (newTranslations.length > 40) {
            const itemsToDiscard = newTranslations.slice(0, newTranslations.length - 40)
            const hasUnsaved = itemsToDiscard.some(item => item.isModified)
            
            if (hasUnsaved) {
              confirm({
                title: '您有未保存的修改',
                icon: <ExclamationCircleOutlined />,
                content: '继续加载将丢失这些未保存的修改。您确定要继续吗？',
                okText: '确认丢弃',
                cancelText: '取消',
                onOk: () => setTranslations(newTranslations.slice(-40)),
                onCancel: () => {}
              })
            } else {
              setTranslations(newTranslations.slice(-40))
            }
          } else {
            setTranslations(newTranslations)
          }
        } else if (direction === 'up') {
          setHasMoreUp(fetchedPageNum > 1)
          
          const prevScrollHeight = scrollContainerRef.current?.scrollHeight || 0
          const newTranslations = [...enhancedData, ...translations]

          const applyUpdate = (list, shouldDecrementPage) => {
            if (shouldDecrementPage) {
              setCurrentPage(p => p - 1)
            }
            setTranslations(list)
            setTimeout(() => {
              if (scrollContainerRef.current) {
                const newScrollHeight = scrollContainerRef.current.scrollHeight
                const scrollDiff = newScrollHeight - prevScrollHeight
                scrollContainerRef.current.scrollTop += scrollDiff
              }
            }, 50)
          }

          if (newTranslations.length > 40) {
            const itemsToDiscard = newTranslations.slice(40)
            const hasUnsaved = itemsToDiscard.some(item => item.isModified)

            if (hasUnsaved) {
              confirm({
                title: '您有未保存的修改',
                icon: <ExclamationCircleOutlined />,
                content: '继续加载将丢失这些未保存的修改。您确定要继续吗？',
                okText: '确认丢弃',
                cancelText: '取消',
                onOk: () => applyUpdate(newTranslations.slice(0, 40), true),
                onCancel: () => {}
              })
            } else {
              applyUpdate(newTranslations.slice(0, 40), true)
            }
          } else {
            applyUpdate(newTranslations, false)
          }
        } else { // replace
          setTranslations(enhancedData)
          setCurrentPage(fetchedPageNum)
          setHasMoreUp(fetchedPageNum > 1)
          setHasMoreDown(fetchedPageNum * 20 < total)
        }
      } else {
        message.error('加载数据失败')
      }
    } catch (error) {
      console.error('Error loading translations:', error)
      message.error('加载数据时发生错误')
    } finally {
      setIsLoading(false)
      setIsScrolling(false)
    }
  }, [isLoading, proofreadFilter, searchTerm, editorId])

  // 滚动事件处理
  const handleScroll = useCallback(async () => {
    if (isLoading || isScrolling) return
    
    const container = scrollContainerRef.current
    if (!container) return

    const { scrollTop, scrollHeight, clientHeight } = container
    
    if (scrollHeight <= clientHeight) return
    
    const scrollPercentage = scrollTop / (scrollHeight - clientHeight)

    if (scrollPercentage > 0.8 && hasMoreDown) {
      await loadTranslations(currentPage + 1, searchTerm, 'down')
    }
    else if (scrollPercentage < 0.2 && hasMoreUp) {
      const numPages = Math.ceil(translations.length / 20)
      const firstPageInView = currentPage - numPages + 1
      const pageToFetch = firstPageInView - 1
      if (pageToFetch >= 1) {
        await loadTranslations(pageToFetch, searchTerm, 'up')
      }
    }
  }, [isLoading, isScrolling, hasMoreUp, hasMoreDown, currentPage, searchTerm, loadTranslations])

  // 当 editorId、筛选器或搜索词变化时，重新加载数据
  useEffect(() => {
    loadTranslations(1, searchTerm, 'replace');
  }, [editorId, proofreadFilter, searchTerm])

  // 搜索处理
  const handleSearch = useCallback(async () => {
    await loadTranslations(1, searchTerm, 'replace')
  }, [searchTerm, loadTranslations])

  // 滚动事件绑定
  useEffect(() => {
    const container = scrollContainerRef.current
    if (container) {
      container.addEventListener('scroll', handleScroll)
      return () => container.removeEventListener('scroll', handleScroll)
    }
  }, [handleScroll])

  // 处理输入变化
  const handleInputChange = (id, value) => {
    setTranslations(currentTranslations => {
      const newTranslations = currentTranslations.map(item => {
        if (item.id === id) {
          return {
            ...item,
            translation: value,
            isModified: value !== item.originalTranslation
          }
        }
        return item
      })

      const changedItem = newTranslations.find(item => item.id === id)
      
      setEditedItems(currentEditedItems => {
        const newEditedItems = new Set(currentEditedItems)
        if (changedItem.isModified) {
          newEditedItems.add(id)
        } else {
          newEditedItems.delete(id)
        }
        setUnsavedCount(newEditedItems.size)
        return newEditedItems
      })
      
      return newTranslations
    })
    
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify({
        type: 'updateTranslation',
        id: id,
        translation: value
      }))
    }
  }

  // 开始编辑
  const handleFocus = (id) => {
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify({ type: 'startEditing', id }))
    }
  }

  // 停止编辑
  const handleBlur = (id) => {
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      ws.current.send(JSON.stringify({ type: 'stopEditing', id }))
    }
  }

  // 切换精校状态
  const toggleProofreadStatus = async (id, currentStatus) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/proofread-status`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, isProofread: !currentStatus })
      });
      const result = await response.json();
      if (result.success) {
        message.success('精校状态已更新');
        setTranslations(prev => 
          prev.map(t => t.id === id ? { ...t, isProofread: !currentStatus } : t)
        );
      } else {
        message.error(result.message || '更新失败');
      }
    } catch (error) {
      console.error('Error toggling proofread status:', error);
      message.error('更新精校状态时出错');
    }
  };

  // 保存单个翻译
  const saveTranslation = async (id) => {
    const item = translations.find(t => t.id === id)
    if (!item) return

    try {
      const response = await fetch(`${API_BASE_URL}/api/translations/save`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: item.id,
          translation: item.translation
        }),
      })

      const result = await response.json()
      
      if (result.success) {
        message.success('保存成功')
        
        // 更新状态，同时更新originalTranslation
        setTranslations(prev => 
          prev.map(t => 
            t.id === id ? { ...t, isModified: false, originalTranslation: t.translation } : t
          )
        )
        
        setEditedItems(prev => {
          const newSet = new Set(prev)
          newSet.delete(id)
          setUnsavedCount(newSet.size)
          return newSet
        })
      } else {
        message.error(result.message || '保存失败')
      }
    } catch (error) {
      console.error('Error saving translation:', error)
      message.error('保存时发生错误')
    }
  }

  // 获取同步配置
  const loadSyncConfig = useCallback(async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/sync-config`)
      const result = await response.json()
      if (result.success) {
        setSyncConfig(result.config)
        form.setFieldsValue(result.config)
      }
    } catch (error) {
      console.error('Error loading sync config:', error)
    }
  }, [form])

  // 保存项目地址
  const saveProjectPath = async (projectPath) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/sync-config/project-path`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ projectPath })
      })
      const result = await response.json()
      if (result.success) {
        setSyncConfig(prev => ({ ...prev, projectPath }))
        message.success('项目地址保存成功')
      } else {
        message.error(result.message || '保存失败')
      }
    } catch (error) {
      console.error('Error saving project path:', error)
      message.error('保存项目地址时发生错误')
    }
  }

  // 保存目标路径
  const saveTargetPath = async (targetPath) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/sync-config/target-path`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ targetPath })
      })
      const result = await response.json()
      if (result.success) {
        setSyncConfig(prev => ({ ...prev, targetPath }))
        message.success('目标路径保存成功')
      } else {
        message.error(result.message || '保存失败')
      }
    } catch (error) {
      console.error('Error saving target path:', error)
      message.error('保存目标路径时发生错误')
    }
  }

  // 从目标项目同步数据到服务器
  const handleSyncFromProject = () => {
    if (!syncConfig.projectPath || !syncConfig.targetPath) {
      message.warning('请先配置项目地址和目标路径')
      return
    }

    // 构建规范的路径显示
    const normalizedPath = `${syncConfig.projectPath}${syncConfig.projectPath.endsWith('\\') || syncConfig.projectPath.endsWith('/') ? '' : '\\'}${syncConfig.targetPath}\\default.json`
    
    const modal = Modal.confirm({
      title: '确认从目标项目同步',
      content: `将会从 ${normalizedPath} 获取最新的翻译文件并同步到服务器。确定继续吗？`,
      icon: <ExclamationCircleOutlined />,
      okText: '确认同步',
      cancelText: '取消',
      onOk: () => {
        // 立即关闭确认弹窗
        modal.destroy()
        
        // 开始同步任务
        setIsSyncing(true)
        setSyncLogs([]) // 清空之前的日志
        setShowSyncLogs(true) // 显示日志窗口
        
        // 异步执行同步任务
        const performSyncFromProject = async () => {
          try {
            const response = await fetch(`${API_BASE_URL}/api/sync-from-project`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(syncConfig)
            })
            const result = await response.json()
            if (result.success) {
              message.success('从目标项目同步成功！数据已更新')
              // 重新加载翻译数据
              loadTranslations(1, searchTerm, 'replace')
            } else {
              message.error(result.message || '同步失败')
            }
          } catch (error) {
            console.error('Error syncing from project:', error)
            message.error('同步时发生错误')
          } finally {
            setIsSyncing(false)
          }
        }
        
        performSyncFromProject()
      }
    })
  }

  // 同步数据
  const handleSyncData = () => {
    if (!syncConfig.projectPath || !syncConfig.targetPath) {
      message.warning('请先配置项目地址和目标路径')
      return
    }

    // 构建规范的路径显示
    const normalizedPath = `${syncConfig.projectPath}${syncConfig.projectPath.endsWith('\\') || syncConfig.projectPath.endsWith('/') ? '' : '\\'}${syncConfig.targetPath}\\default.json`
    
    const modal = Modal.confirm({
      title: '确认同步数据',
      content: `将会把翻译文件同步到 ${normalizedPath}，并执行编译命令。确定继续吗？`,
      icon: <ExclamationCircleOutlined />,
      okText: '确认同步',
      cancelText: '取消',
      onOk: () => {
        // 立即关闭确认弹窗
        modal.destroy()
        
        // 开始同步任务
        setIsSyncing(true)
        setSyncLogs([]) // 清空之前的日志
        setShowSyncLogs(true) // 显示日志窗口
        
        // 异步执行同步任务
        const performSync = async () => {
          try {
            const response = await fetch(`${API_BASE_URL}/api/sync-data`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(syncConfig)
            })
            const result = await response.json()
            if (result.success) {
              message.success('同步成功！请刷新目标项目查看效果')
            } else {
              message.error(result.message || '同步失败')
            }
          } catch (error) {
            console.error('Error syncing data:', error)
            message.error('同步时发生错误')
          } finally {
            setIsSyncing(false)
          }
        }
        
        performSync()
      }
    })
  }

  // 筛选中文内容并下载
  const handleFilterChineseContent = async () => {
    try {
      setIsSyncing(true)
      
      const response = await fetch(`${API_BASE_URL}/api/filter-chinese`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      })
      
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `chinese_content_${new Date().toISOString().slice(0, 10)}.json`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        message.success('中文内容筛选完成，文件已下载')
      } else {
        const result = await response.json()
        message.error(result.message || '筛选失败')
      }
    } catch (error) {
      console.error('Error filtering chinese content:', error)
      message.error('筛选中文内容时发生错误')
    } finally {
      setIsSyncing(false)
    }
  }

  // 下载目标项目的 default.json
  const handleDownloadFromProject = async () => {
    if (!syncConfig.projectPath || !syncConfig.targetPath) {
      message.warning('请先配置项目地址和目标路径')
      return
    }

    try {
      setIsSyncing(true)
      
      const response = await fetch(`${API_BASE_URL}/api/download-project-json`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(syncConfig)
      })
      
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `default_from_project_${new Date().toISOString().slice(0, 10)}.json`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        message.success('目标项目的 default.json 下载完成')
      } else {
        const result = await response.json()
        message.error(result.message || '下载失败')
      }
    } catch (error) {
      console.error('Error downloading project json:', error)
      message.error('下载目标项目文件时发生错误')
    } finally {
      setIsSyncing(false)
    }
  }

  // 下载服务器的 default.json
  const handleDownloadFromServer = async () => {
    try {
      setIsSyncing(true)
      
      const response = await fetch(`${API_BASE_URL}/api/download-server-json`, {
        method: 'GET'
      })
      
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `default_from_server_${new Date().toISOString().slice(0, 10)}.json`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        message.success('服务器的 default.json 下载完成')
      } else {
        const result = await response.json()
        message.error(result.message || '下载失败')
      }
    } catch (error) {
      console.error('Error downloading server json:', error)
      message.error('下载服务器文件时发生错误')
    } finally {
      setIsSyncing(false)
    }
  }

  // 上传文件更新翻译
  const handleUploadUpdate = async (file) => {
    const formData = new FormData()
    formData.append('file', file)
    
    try {
      setIsSyncing(true)
      
      const response = await fetch(`${API_BASE_URL}/api/upload-update`, {
        method: 'POST',
        body: formData
      })
      
      const result = await response.json()
      if (result.success) {
        message.success(`文件上传成功！${result.message}`)
        // 重新加载翻译数据
        loadTranslations(1, searchTerm, 'replace')
      } else {
        message.error(result.message || '上传更新失败')
      }
    } catch (error) {
      console.error('Error uploading file:', error)
      message.error('上传文件时发生错误')
    } finally {
      setIsSyncing(false)
    }
    
    return false // 阻止默认上传行为
  }

  // 加载同步配置
  useEffect(() => {
    loadSyncConfig()
  }, [loadSyncConfig])

  const displayedCount = translations.length

  return (
    <div className="translation-editor">
      {/* 固定头部 */}
      <div className="editor-header">
        <h1>翻译编辑器</h1>
        
        {/* 搜索区域 */}
        <div className="search-section">
          <Input.Search
            placeholder="搜索中文内容、ID或英文翻译..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onSearch={handleSearch}
            onPressEnter={handleSearch}
            enterButton={<SearchOutlined />}
            size="large"
            allowClear
          />
        </div>

        {/* 筛选区域 */}
        <div className="filter-section">
          <Radio.Group 
            onChange={(e) => setProofreadFilter(e.target.value)} 
            value={proofreadFilter}
            buttonStyle="solid"
          >
            <Radio.Button value="not_proofread">未精校</Radio.Button>
            <Radio.Button value="proofread">已精校</Radio.Button>
            <Radio.Button value="all">全部</Radio.Button>
          </Radio.Group>
        </div>

        {/* 状态信息 */}
        <div className="status-info">
          <div className="count-info">
            <Text>当前显示: {displayedCount} 条</Text>
            <Text>总计: {totalCount} 条</Text>
            {unsavedCount > 0 && (
              <Text type="warning">未保存: {unsavedCount} 条</Text>
            )}
          </div>
          
          {/* 滚动指示器 */}
          <div className="scroll-indicators">
            {hasMoreUp && (
              <div className="scroll-indicator up">
                <ArrowUpOutlined />
                <span>向上滚动加载更多</span>
              </div>
            )}
            {hasMoreDown && (
              <div className="scroll-indicator down">
                <ArrowDownOutlined />
                <span>向下滚动加载更多</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 翻译列表 */}
      <div className="translation-list" ref={scrollContainerRef}>
        {isLoading && translations.length === 0 ? (
          <div className="loading-container">
            <Spin size="large" />
            <p>加载中...</p>
          </div>
        ) : (
          <>
            {translations.map((item) => {
              const isDisabled = lockedItems.has(item.id);

              return (
                <Card 
                  key={item.id} 
                  className={`translation-item ${item.isModified ? 'modified' : ''} ${isDisabled ? 'locked' : ''}`}
                  size="small"
                >
                  <div className="item-header">
                  ID {item.id}&nbsp;&nbsp;{item.chinese}
                  </div>
                  
                  <div className="item-content">
                    <div className="english-input">
                      <Input
                        value={item.translation}
                        onChange={(e) => handleInputChange(item.id, e.target.value)}
                        onFocus={() => handleFocus(item.id)}
                        onBlur={() => handleBlur(item.id)}
                        placeholder="输入英文翻译..."
                        size="large"
                        disabled={isDisabled}
                      />
                    </div>
                    
                    <div className="save-button">
                      <Button
                        type={item.isModified ? "primary" : "default"}
                        icon={<SaveOutlined />}
                        onClick={() => saveTranslation(item.id)}
                        disabled={!item.isModified || isDisabled}
                        size="large"
                      >
                        保存
                      </Button>
                      <Button 
                        onClick={() => toggleProofreadStatus(item.id, item.isProofread)}
                        type={item.isProofread ? "dashed" : "default"}
                        danger={item.isProofread}
                        size="large"
                        style={{ marginLeft: '8px' }}
                        disabled={isDisabled}
                      >
                        {item.isProofread ? '已精校' : '未精校'}
                      </Button>
                    </div>
                  </div>
                </Card>
              )
            })}
            
            {isLoading && (
              <div className="loading-more">
                <Spin />
                <span>加载更多...</span>
              </div>
            )}
          </>
        )}
      </div>

      {/* 右下角浮动按钮 */}
      <FloatButton
        icon={<SettingOutlined />}
        tooltip="数据同步设置"
        onClick={() => setSyncDrawerVisible(true)}
        style={{
          right: 24,
          bottom: 24,
        }}
      />

      {/* 同步设置抽屉 */}
      <Drawer
        title="数据同步设置"
        placement="right"
        width={450}
        onClose={() => setSyncDrawerVisible(false)}
        open={syncDrawerVisible}
      >
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              key: '1',
              label: '纠正翻译',
              children: (
                <div>
                  <Form form={form} layout="vertical">
                    <Form.Item
                      label="目标项目地址"
                      name="projectPath"
                      rules={[{ required: true, message: '请输入项目地址' }]}
                    >
                      <Input.Group compact>
                        <Input
                          style={{ width: 'calc(100% - 60px)' }}
                          placeholder="例如: E:\项目\study-preview\"
                          value={syncConfig.projectPath}
                          onChange={(e) => setSyncConfig(prev => ({ ...prev, projectPath: e.target.value }))}
                        />
                        <Button
                          type="primary"
                          style={{ width: '60px' }}
                          onClick={() => saveProjectPath(syncConfig.projectPath)}
                        >
                          确定
                        </Button>
                      </Input.Group>
                    </Form.Item>

                    <Form.Item
                      label="具体目标路径"
                      name="targetPath"
                      rules={[{ required: true, message: '请输入目标路径' }]}
                    >
                      <Input.Group compact>
                        <Input
                          style={{ width: 'calc(100% - 60px)' }}
                          placeholder="例如: src\languages\translates\messages"
                          value={syncConfig.targetPath}
                          onChange={(e) => setSyncConfig(prev => ({ ...prev, targetPath: e.target.value }))}
                        />
                        <Button
                          type="primary"
                          style={{ width: '60px' }}
                          onClick={() => saveTargetPath(syncConfig.targetPath)}
                        >
                          确定
                        </Button>
                      </Input.Group>
                    </Form.Item>

                    <Divider />

                    <Button
                      type="primary"
                      icon={<SyncOutlined />}
                      size="large"
                      loading={isSyncing}
                      onClick={handleSyncData}
                      block
                      disabled={!syncConfig.projectPath || !syncConfig.targetPath}
                    >
                      同步到目标项目
                    </Button>

                    <div style={{ marginTop: 16, color: '#666', fontSize: '12px' }}>
                      <p>功能说明：</p>
                      <ul>
                        <li>配置目标项目的地址和路径</li>
                        <li><strong>同步到目标项目：</strong>将当前翻译结果同步到目标项目，方便查看翻译效果</li>
                        <li>翻译人员完成翻译后，点击同步按钮即可在目标项目中预览效果</li>
                      </ul>
                    </div>
                  </Form>
                </div>
              ),
            },
            {
              key: '2',
              label: '准备翻译',
              children: (
                <div>
                  <Form form={form} layout="vertical">
                    <Form.Item
                      label="目标项目地址"
                      name="projectPath"
                      rules={[{ required: true, message: '请输入项目地址' }]}
                    >
                      <Input.Group compact>
                        <Input
                          style={{ width: 'calc(100% - 60px)' }}
                          placeholder="例如: E:\项目\study-preview\"
                          value={syncConfig.projectPath}
                          onChange={(e) => setSyncConfig(prev => ({ ...prev, projectPath: e.target.value }))}
                        />
                        <Button
                          type="primary"
                          style={{ width: '60px' }}
                          onClick={() => saveProjectPath(syncConfig.projectPath)}
                        >
                          确定
                        </Button>
                      </Input.Group>
                    </Form.Item>

                    <Form.Item
                      label="具体目标路径"
                      name="targetPath"
                      rules={[{ required: true, message: '请输入目标路径' }]}
                    >
                      <Input.Group compact>
                        <Input
                          style={{ width: 'calc(100% - 60px)' }}
                          placeholder="例如: src\languages\translates\messages"
                          value={syncConfig.targetPath}
                          onChange={(e) => setSyncConfig(prev => ({ ...prev, targetPath: e.target.value }))}
                        />
                        <Button
                          type="primary"
                          style={{ width: '60px' }}
                          onClick={() => saveTargetPath(syncConfig.targetPath)}
                        >
                          确定
                        </Button>
                      </Input.Group>
                    </Form.Item>

                    <Divider />

                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                      <Button
                        type="default"
                        icon={<ArrowDownOutlined />}
                        size="large"
                        loading={isSyncing}
                        onClick={handleSyncFromProject}
                        block
                        disabled={!syncConfig.projectPath || !syncConfig.targetPath}
                      >
                        从目标项目同步
                      </Button>
                      
                      <Divider style={{ margin: '12px 0' }}>文件下载</Divider>
                      
                      <Button
                        type="default"
                        icon={<DownloadOutlined />}
                        size="large"
                        loading={isSyncing}
                        onClick={handleDownloadFromProject}
                        block
                        disabled={!syncConfig.projectPath || !syncConfig.targetPath}
                      >
                        下载目标项目 default.json
                      </Button>
                      
                      <Button
                        type="default"
                        icon={<DownloadOutlined />}
                        size="large"
                        loading={isSyncing}
                        onClick={handleDownloadFromServer}
                        block
                        style={{ marginTop: 8 }}
                      >
                        下载服务器 default.json
                      </Button>
                      
                      <Divider style={{ margin: '12px 0' }}>翻译内容处理</Divider>
                      
                      <Button
                        type="default"
                        icon={<FilterOutlined />}
                        size="large"
                        loading={isSyncing}
                        onClick={handleFilterChineseContent}
                        block
                      >
                        筛选中文内容并下载
                      </Button>
                      
                      <Upload
                        beforeUpload={handleUploadUpdate}
                        accept=".json"
                        showUploadList={false}
                        disabled={isSyncing}
                      >
                        <Button
                          type="default"
                          icon={<UploadOutlined />}
                          size="large"
                          loading={isSyncing}
                          block
                        >
                          上传文件更新翻译
                        </Button>
                      </Upload>
                      
                      <Divider style={{ margin: '12px 0' }}>发布到项目</Divider>
                      
                      <Button
                        type="primary"
                        icon={<SyncOutlined />}
                        size="large"
                        loading={isSyncing}
                        onClick={handleSyncData}
                        block
                        disabled={!syncConfig.projectPath || !syncConfig.targetPath}
                      >
                        同步到目标项目
                      </Button>
                    </Space>

                    <div style={{ marginTop: 16, color: '#666', fontSize: '12px' }}>
                      <div style={{ marginBottom: '12px', padding: '12px', backgroundColor: '#f0f8ff', borderRadius: '6px', border: '1px solid #d9d9d9' }}>
                        <p style={{ margin: '0 0 8px 0', fontWeight: 'bold', color: '#1890ff' }}>📋 完整工作流程：</p>
                        <ol style={{ margin: 0, paddingLeft: '20px', lineHeight: '1.6' }}>
                          <li><strong>在目标项目执行提取：</strong> <code>npx voerkai18n extract</code></li>
                          <li><strong>从目标项目同步：</strong> 将提取生成的最新 default.json 同步到翻译服务器</li>
                          <li><strong>筛选中文内容：</strong> 筛选需要翻译的中文条目并下载（可选）</li>
                          <li><strong>翻译处理：</strong> 可以上传文件批量更新，或在界面中手动翻译</li>
                          <li><strong>同步到目标项目：</strong> 将完成的翻译发布到目标项目并自动编译</li>
                        </ol>
                      </div>
                      
                      <p><strong>功能详细说明：</strong></p>
                      <ul>
                        <li><strong>从目标项目同步：</strong>获取项目执行 extract 命令后生成的最新翻译文件</li>
                        <li><strong>下载目标项目 default.json：</strong>直接下载目标项目中的翻译文件到本地</li>
                        <li><strong>下载服务器 default.json：</strong>下载服务器当前的翻译文件到本地</li>
                        <li><strong>筛选中文内容：</strong>从服务器翻译文件中筛选出包含中文的条目，生成待翻译清单</li>
                        <li><strong>上传文件更新：</strong>上传处理好的翻译文件，系统会按 ID 自动匹配更新</li>
                        <li><strong>同步到目标项目：</strong>将最终翻译文件发布到项目，自动执行编译生成语言包</li>
                      </ul>
                      
                      <div style={{ marginTop: '8px', padding: '8px', backgroundColor: '#fff7e6', borderRadius: '4px', border: '1px solid #ffd591' }}>
                        <p style={{ margin: 0, fontSize: '11px', color: '#d48806' }}>
                          💡 <strong>提示：</strong>第3、4步可以灵活选择 - 既可以下载文件离线翻译后上传，也可以直接在翻译界面中手动编辑
                        </p>
                      </div>
                    </div>
                  </Form>
                </div>
              ),
            },
          ]}
        />
      </Drawer>

      {/* 同步日志窗口 */}
      <Modal
        title="同步进度"
        open={showSyncLogs}
        onCancel={() => setShowSyncLogs(false)}
        footer={[
          <Button key="close" onClick={() => setShowSyncLogs(false)}>
            关闭
          </Button>
        ]}
        width={800}
        style={{ top: 20 }}
      >
        <div style={{ 
          height: '400px', 
          overflow: 'auto', 
          backgroundColor: '#1f1f1f', 
          color: '#ffffff', 
          padding: '12px',
          fontFamily: 'Consolas, Monaco, monospace',
          fontSize: '12px',
          lineHeight: '1.4'
        }}>
          {syncLogs.length === 0 ? (
            <div style={{ color: '#666', textAlign: 'center', marginTop: '50px' }}>
              等待同步开始...
            </div>
          ) : (
            syncLogs.map((log, index) => (
              <div key={index} style={{ marginBottom: '4px' }}>
                <span style={{ color: '#888' }}>[{log.timestamp}]</span>{' '}
                <span style={{ 
                  color: log.message.includes('✅') ? '#52c41a' :
                         log.message.includes('❌') ? '#ff4d4f' :
                         log.message.includes('⚠️') ? '#faad14' :
                         log.message.includes('🎉') ? '#1890ff' : '#ffffff'
                }}>
                  {log.message}
                </span>
              </div>
            ))
          )}
          {isSyncing && (
            <div style={{ 
              color: '#1890ff', 
              textAlign: 'center', 
              marginTop: '10px',
              animation: 'blink 1s infinite'
            }}>
              ▋ 同步进行中...
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}

export default TranslationEditor 